package Dm

import (
	"fmt"
	"db2s/ETL"
	"db2s/global"
	"strings"
)

func (or TableInfoMeta) SeqExist(s global.TablesMetaInfoInput) (result global.ObjectExistReturnResult, err error) {
	var f1 any
	var event = "[oracleSeqExist]"
	for _, v := range []string{
		"ALL_SEQUENCES",
		"DBA_SEQUENCES",
	} {
		result.BaseResult.Sql = fmt.Sprintf("select count(1) as \"sum\" from %v where SEQUENCE_OWNER = '%v' AND SEQUENCE_NAME='%v'", v, s.TableInfo.Schema, s.TableInfo.Table)
		if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
			Ss:           s,
			Event:        event,
			SelectSqlStr: result.BaseResult.Sql,
			Expect:       ETL.Map,
		}); err != nil || f1 == nil || fmt.Sprintf("%v", f1.(map[string]any)["sum"]) == "0" {
			continue
		}
		if fmt.Sprintf("%v", f1.(map[string]any)["sum"]) == "1" {
			result.Result = true
		}
		break
	}
	return
}
func (or TableInfoMeta) SeqName(s global.TablesMetaInfoInput) (result global.ObjectNameReturnResult, err error) {
	var f1 any
	var event = "[oracleSeqName]"
	for _, v := range []string{"ALL_SEQUENCES", "DBA_SEQUENCES",
	} {
		result.BaseResult.Sql = fmt.Sprintf("select SEQUENCE_NAME from %v where  SEQUENCE_OWNER ='%v' %v",
			v, s.TableInfo.Schema, func() string {
				switch {
				case s.TableInfo.Table == "*":
					return ""
				case strings.Contains(s.TableInfo.Table, "%"):
					return fmt.Sprintf(" and SEQUENCE_NAME like '%%%v%%'", s.TableInfo.Table)
				default:
					return fmt.Sprintf(" and SEQUENCE_NAME = '%v'", s.TableInfo.Table)
				}
			}())
		if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
			Ss:           s,
			Event:        event,
			SelectSqlStr: result.BaseResult.Sql,
			Expect:       ETL.StringGarth,
		}); err != nil || f1 == nil || len(f1.([]string)) == 0 {
			continue
		}
		result.Result = f1.([]string)
		break
	}
	return
}
func seqPrintInfo(x global.SeqResultDefinition) string {
	var (
		cache = "NOCACHE"
		order = "NOORDER"
		cycle = "NOCYCLE"
	)
	if x.CacheSize != "0" {
		cache = fmt.Sprintf("CACHE %v", x.CacheSize)
	}
	if x.OrderFlag != "N" {
		order = "ORDER"
	}
	if x.CycleFlag != "N" {
		cycle = "CYCLE"
	}
	return fmt.Sprintf("CREATE SEQUENCE \"%v\".\"%v\" \n"+
		"\t MINVALUE %v \n"+
		"\t MAXVALUE %v \n"+
		"\t INCREMENT BY %v \n"+
		"\t START WITH %v \n "+
		"\t %v %v %v \n", x.Schema, x.Name, x.MinValue, x.MaxValue, x.IncrementBy, x.StartValue, cache, order, cycle)
}
func (or SchemaObjectMeta) Seq(s global.SchemaObjectInput) (result global.SchemaObjectReturnResult, err error) {
	var (
		f1    any
		x     global.SeqResultDefinition
		event = "[oracleSeq]"
	)
	for _, v := range []string{
		"all_sequences",
		"dba_sequences",
	} {
		result.BaseResult.Sql = fmt.Sprintf("SELECT \n"+
			"\tSEQUENCE_OWNER AS \"schema\",\n"+
			"\tSEQUENCE_NAME AS \"name\",\n"+
			"\tMIN_VALUE AS \"minValue\",\n"+
			"\tMAX_VALUE AS \"maxValue\",\n"+
			"\tINCREMENT_BY AS \"incrementBy\",\n"+
			"\tCYCLE_FLAG AS \"cycleFlag\",\n"+
			"\tORDER_FLAG AS \"orderFlag\",\n"+
			"\tCACHE_SIZE AS \"cacheSize\",\n"+
			"\tLAST_NUMBER AS \"startValue\" \n"+
			"\tFROM  \n"+
			"\t %v \n"+
			"\t WHERE \n"+
			"\t SEQUENCE_OWNER='%v' and SEQUENCE_NAME='%v'", v, s.Schema, s.Table)
		if result.BaseResult.TimeOut, f1, err = ExecSelectSql(ExecSqlInputS{
			Ss:           s,
			Event:        event,
			SelectSqlStr: result.BaseResult.Sql,
			Expect:       ETL.Map,
		}); err != nil || f1 == nil || len(f1.(map[string]any)) == 0 {
			continue
		}
		if err = global.MapSubToStructSubJsonName(mapNullActive(f1.(map[string]any)), &x); err != nil {
			return
		}
		x.Type = "seq"
		x.PrintInfo = seqPrintInfo(x)
		break
	}
	result.SeqResult.Definition = x
	result.SeqResult.Convert = global.SeqDefinitionConvertS{
		Schema:      x.Schema,
		Name:        x.Name,
		MinValue:    x.MinValue,
		MaxValue:    x.MaxValue,
		IncrementBy: x.IncrementBy,
		CycleFlag:   x.CycleFlag,
		OrderFlag:   x.OrderFlag,
		CacheSize:   x.CacheSize,
		StartValue:  x.StartValue,
		Type:        x.Type,
		PrintInfo:   x.PrintInfo,
	}
	return
}
